package com.bit.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bit.captcha.mdoel.CaptchaProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaProperties captchaProperties;
    private static long VILID_MILLIS_TIME = 5 * 60 * 1000; //5分钟

    @RequestMapping("/getCaptcha")
    public void genCaptcha(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        String code = lineCaptcha.getCode();
        //图形验证码写出，可以写出到文件，也可以写出到流
        try {
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "No-cache");
            lineCaptcha.write(response.getOutputStream());
            System.out.println(code);
            //写入到session
            session.setAttribute(captchaProperties.getSession().getCode(), code);
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session){
        System.out.println("用户输入验证码: "+ captcha);
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        //从session中获取
        String code = (String)session.getAttribute(captchaProperties.getSession().getCode());
        long date = (long)session.getAttribute(captchaProperties.getSession().getDate());
        if (captcha.equalsIgnoreCase(code) && (System.currentTimeMillis()-date < VILID_MILLIS_TIME)) {
            return true;
        }
        return false;
    }
}
